package com.huanghuai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huanghuai.entity.SysUser;
import com.huanghuai.service.SysMenuService;
import com.huanghuai.service.SysUserService;
import com.huanghuai.vo.SecurityUser;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SecurityUserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SysUserService sysUserService;
    @Resource
     private SysMenuService sysMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername,username);
        SysUser sysUser = sysUserService.getOne(queryWrapper);
        if(sysUser==null){
            throw new UsernameNotFoundException("该用户不存在");
        }
        List<String> userPermissions = sysMenuService.queryPermissionsByUserId(sysUser.getUserId());
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        for (String userPermission : userPermissions) {
            SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userPermission);
            authorityList.add(simpleGrantedAuthority);
        }
//        List<SimpleGrantedAuthority> authorityList1 = userPermissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        SecurityUser securityUser = new SecurityUser(sysUser);
        securityUser.setAuthorityList(authorityList);
        return securityUser;
    }
}
